<?php
/*
 *  Pictet2
 *
 *	Filename: index.php
 *	Description: does everything pretty much.
 *	SVN: Revision $WCREV$ on $WCDATE$
 *
 *
 *	License (MIT License)
 *
 *	Copyright (c) 2007 CMI
 *
 *	Permission is hereby granted, free of charge, to any person obtaining
 *	a copy of this software and associated documentation files (the "Software"),
 *	to deal in the Software without restriction, including without limitation the
 *	rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 *	sell copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 *	INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 *	PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 *	CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 *	OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 *  Compiled on: ###COMPILEDATE###
 *
 */

/**
 * The root directory that the script exists in.
 *
 */
define("ROOT_DIR", dirname(__FILE__));
/**
 * Shortcut for the DIRECTORY_SEPARATOR constant.
 *
 */
define("DS", DIRECTORY_SEPARATOR);

/**
 * PHP magic autoload function to load classes.
 *
 * @param string $className
 */
function __autoload($className) {
    if(file_exists(ROOT_DIR . DS . "." . str_replace("_", DS ,$className) . ".php")) {
        include_once(ROOT_DIR . DS . "." . str_replace("_", DS ,$className) . ".php");
    }
}

/**
 * Pictet2 Singleton Class
 *
 * The Pictet2 Singleton Class handles the life cycle of the entire request and dependent on options, handles output to the browsers.
 */
class Pictet2 {

    /**
     * The instance of the Pictet2 class.
     *
     * @var object
     */
    static private $_instance;

    private $_output;

    /**
     * Pictet2 Constructor, recieves URI for images to pass on to the location handler. It also loads the settings and passes them into the Pictet2 registry.
     *
     * @param string $uri
     */
    private function __construct($uri) {
        $this->_htaccess();
        
        if(strstr($uri, "?")) {
            $uri = substr($uri, 0, strpos($uri, "?"));
        }
        
        define("URL_BASE_DIR", substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], basename($_SERVER["PHP_SELF"]))));
        $uri = substr($uri, strlen(URL_BASE_DIR));
        $uri = rtrim($uri, "/");
        $uri = ltrim($uri, "/");
        $uri = urldecode($uri);
        if($uri) {
            $parts = split("/", $uri);
        }
        $x = 0;
        if(is_numeric($parts[sizeof($parts)-1]) && $parts[sizeof($parts)-1] > 0) {
            define("GALLERY_PAGE", array_pop($parts));
        } else {
            define("GALLERY_PAGE", 1);
        }
        while(!$className && $x <= sizeof($parts)-1) {
            if(class_exists("Plugins_Controllers_" . ucfirst($parts[$x]))) {
                $className = "Plugins_Controllers_" . ucfirst($parts[$x]);
            } elseif(class_exists("Pictet2_Controllers_" . ucfirst($parts[$x]))) {
                $className = "Pictet2_Controllers_" . ucfirst($parts[$x]);
            }
            ++$x;
        }

        if(!$className) {
            $className = "Default";
            if(class_exists("Plugins_Controllers_" . ucfirst($className))) {
                $className = "Plugins_Controllers_" . ucfirst($className);
            } elseif(class_exists("Pictet2_Controllers_" . ucfirst($className))) {
                $className = "Pictet2_Controllers_" . ucfirst($className);
            }
            $x = 0;
        }
        if($parts) {
            if($x) {
                $workingDir = implode(DS, array_slice($parts, 0, $x-1));
                $urlFolder = implode("/", array_slice($parts, 0, $x-1));
            } else {
                $workingDir = implode(DS, $parts);
                $urlFolder = implode("/", $parts);
            }

            if($urlFolder) {
                define("URL_CURRENT_DIR", URL_BASE_DIR . $urlFolder . "/");
            } else {
                define("URL_CURRENT_DIR", URL_BASE_DIR);
            }
            $params = array_slice($parts, $x);
            if(is_dir(ROOT_DIR . DS . $workingDir)) {
                chdir(ROOT_DIR . DS . $workingDir);
            } else {
                throw new Exception("Folder: " . $workingDir . " is not a directory!");
            }
        } else {
            define("URL_CURRENT_DIR", URL_BASE_DIR);
        }
        ob_start();
        new $className($urlFolder, $params);
        $this->_output = ob_get_clean();
    }

    /**
     * Static method to get singleton instance.
     *
     * @param string $uri
     * @return Pictet2
     */
    public static function getInstance($uri) {
        if(null == self::$_instance) {
            self::$_instance = new Pictet2($uri);
        }
        return self::$_instance;
    }

    /**
     * Renders the output.
     *
     */
    public function render() {
        print $this->_output;
    }

    /**
     * Returns a class name depending if it exists first in the plugins folder then in the main folder.
     *
     * @param string $className
     * @return string
     */
    public static function getClassName($className) {
        if(class_exists("Plugins_" . ucfirst($className))) {
            $className = "Plugins_" . ucfirst($className);
        } elseif(class_exists("Pictet2_" . ucfirst($className))) {
            $className = "Pictet2_" . ucfirst($className);
        } else {
            return false;
        }
        return $className;
    }

    /**
     * Private method to spit out htaccess file needed by Pictet.
     *
     */
    private function _htaccess() {
        if(!file_exists(".htaccess")) {
            file_put_contents(".htaccess", "php_flag cgi.fix_pathinfo 1\nOptions +FollowSymlinks\nRewriteEngine on\nRewriteCond %{SCRIPT_FILENAME} !-f\nRewriteRule .* " . $_SERVER["SCRIPT_NAME"] . " [L]");
        }
    }
}

###COMPILEBLOCK###

if(!($view = Pictet2_Settings::getSetting("ViewEngine"))) {
    $view = "Html";
}

$view = Pictet2::getClassName("Views_" . $view);

$view = new $view();

Pictet2_Registry::setRegistry("view", $view);

$pictet2 = Pictet2::getInstance($_SERVER["REQUEST_URI"]);
//header("Content-Type: text/plain");
$pictet2->render();


